import sys
from pathlib import Path
from os.path import dirname, abspath
path = dirname(str(Path(__file__).resolve().parents[1]))
if path not in sys.path:
    sys.path.append(path)
from requests import Session
from xkw_data_query.config_parse import get_es_config
from xkw_data_query.es.es_dto import EsParam


class ESCaller:
    def __init__(self, appId: str):
        self.session = Session()
        account = get_es_config(appId)
        self.host = account["host"]
        self.username = account["username"]
        self.password = account["password"]
        self.login(self.username, self.password)

    def get(self, url: str, params: dict = None):
        return self.session.get(self.host + url, params=params)
    
    def login(self, username: str, password: str):
        url = f"{self.host}/api/security/v1/login"
        data = {
            "username": username,
            "password": password
        }
        headers = {
            "Content-Type": "application/json",
            "cookie": "xkw-device-id=E75F6C2A25254E577D49498F723C0AD8; UT1=ut-713951-TwJC0dbkLFSXyw; xk.identity=%7b%7d; xkw-fs-id=41264d3a68c06a8a3e8313f660291d9d",
            "kbn-version": "7.4.2",
            "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36"
        }
        response = self.session.post(url, json=data, headers=headers)
        cookies = self.session.cookies.get_dict()
        if response.status_code != 204:
            print(response.text)
            raise Exception("Login failed")
        self.session.get(f"{self.host}/app/kibana")
        headers["cookie"] = headers["cookie"] + f"; sid={cookies['sid']}"
        self.headers = headers
    
    def logout(self):
        pass
    
    def searchWithBody(self, index: str, body: dict):
        res = self.session.post(self.host + f"/api/console/proxy?path=/{index}/_search&method=POST", json=body, headers=self.headers)
        if res.status_code != 200:
            raise Exception(f"search failed: code={res.status_code}, text={res.text}")
        hits = res.json()['hits']
        return {
            "hits": hits["hits"],
            "total": hits["total"]["value"]
        }
    
    def search(self, param: EsParam):
        body = param.get_body()
        index = param.get_index()
        res = self.session.post(self.host + f"/api/console/proxy?path=/{index}/_search&method=POST", json=body, headers=self.headers)
        if res.status_code != 200:
            raise Exception(f"search failed: code={res.status_code}, text={res.text}")
        hits = res.json()['hits']
        return {
            "hits": hits["hits"],
            "total": hits["total"]["value"]
        }
    
if __name__ == "__main__":
    # test()
    # caller = ESCaller("https://opsadm.xkw.com/rbmes")
    # caller.login("mp-rbm", "bB2*rO7^bA0@oB2!cA8]")
    caller = ESCaller("rbm")
    # res = caller.searchWithBody("rbm_resource_query", {"query": {"term": {"id": "34604707"}}})
    param = EsParam("rbm_resource_query")
    # param.add_term("id", "34604708", not_=True)
    # param.add_terms("id", ["34604707", "34604708"]).range_gt("id", "34604705").add_source("id").add_source("title").set_from(0).set_size(10).add_sort("id", "desc")
    param.add_term("year", 2024).add_term("areaIds", "320000").add_term("scenarioId", "420408").add_term("status", "P4_2").add_term("courseId", 32).set_from(0).set_size(50).add_sort("id", "desc")
    res = caller.search(param)
    print(res["total"])

    # search_qbm()